package com.bdqn.controller;

import com.bdqn.base.Email;
import com.bdqn.base.R;
import com.bdqn.logger.WebLogger;
import com.bdqn.feign.FeignPaymentService;
import com.bdqn.rabbitmq.EmailRabbitMQService;
import com.bdqn.service.OrderService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * OrderController
 *
 * @author LILIBO
 * @since 2023-03-09
 */
@RefreshScope // 实现配置的自动更新
@RestController
@RequestMapping("/order")
public class OrderController {

    @Value("${server.port}")
    private String serverPort;

    @Value("${system.mail.to}")
    private String emailTo;

    /**
     * 调用本地服务
     */
    @Resource
    private OrderService orderService;

    /**
     * 调用远程服务（引入目标服务Proxy完成Feign调用）
     */
    @Resource
    private FeignPaymentService feignPaymentService;

    /**
     * 调用远程服务
     */
    @Resource
    private EmailRabbitMQService emailRabbitMQService;

    /**
     * 创建订单（调用支付模块完成订单支付）
     *
     * @param money 订单金额
     * @return
     */
    @WebLogger("创建订单（调用支付模块完成订单支付）")
    @PostMapping("/gen")
    public R genOrder(@RequestParam("money") Double money) {
        // 调用本地服务 生成订单
        String orderId = orderService.genOrderId();

        // 调用远程服务 完成订单支付
        R result = feignPaymentService.payByOrderId(orderId, money);
        if (result.getCode() != 0) {
            return R.failure("【订单模块 - " + serverPort + "】（支付失败）订单: " + orderId + " ，请稍后再试~");
        }

        // 订单支付成功，将消息发送到MQ，给用户发送邮件
        Email email = new Email();
        email.setTo(emailTo);
        email.setContent("【SpringCloud】订单（" +orderId+ "）支付成功！金额：" + money);
        emailRabbitMQService.publishMQMail(email); // 将消息发送到消息队列
        return R.success("【订单模块 - " + serverPort + "】（已支付）订单: " + orderId + " （支付金额: " + money + "） 发送邮件: -----> " + emailTo, orderId);
    }
}
